package com.grouuu.data;

import com.grouuu.geom.Rectangle;
import com.grouuu.world.World;
import haxe.Json;
import js.Browser;
import js.Error;
import js.html.CanvasElement;
import js.html.CanvasRenderingContext2D;
import js.html.ImageData;
import js.html.ImageElement;
import js.html.Rect;
import js.html.Uint8ClampedArray;

/**
 * ...
 * @author Grouuu
 */
class MapData
{
	private var mapTile:Dynamic;
	private var listTiles:Map<String, Dynamic>;
	private var mapPick:CanvasRenderingContext2D;
	private var bufferTileID:Map<String, String>;

	public function new(data:String) 
	{
		bufferTileID = new Map<String, String>();
		
		try
		{
			var json:Dynamic = Json.parse(data);
			
			var tiles:Array<Dynamic> = cast json.tiles;
			
			parseTiles(tiles);
		}
		catch (error:Error)
		{
			trace("Erreur lors du traitement des données : " + error.message);
		}
	}
	
	private function parseTiles(tiles:Array<Dynamic>):Void
	{
		listTiles = new Map<String, Dynamic>();
		
		var color:String;
		
		for (t in tiles)
		{
			color = t.color;
			
			if (color != null)
				listTiles.set(color, t);
			else if (t.name == "MAP")
				mapTile = t;
		}
	}
	
	// CONTROL ////////////////////////////////////////////////////////////////////////////////////
	
	public function setMap(mapImage:ImageElement) 
	{
		var canvas:CanvasElement = Browser.document.createCanvasElement();
		canvas.width = mapTile.width;
		canvas.height = mapTile.height;
		mapPick = canvas.getContext2d();
		
		mapPick.drawImage(mapImage, mapTile.x, mapTile.y, mapTile.width, mapTile.height, 0, 0, mapTile.width, mapTile.height);
	}
	
	// UTIL ///////////////////////////////////////////////////////////////////////////////////////
	
	public function getTileCoord(id:String):Rectangle
	{
		var tile:Dynamic = listTiles.get(id);
		
		return (tile == null) ? null : new Rectangle(tile.x, tile.y, 32, 32);
	}
	
	public function getTileID(x:Int, y:Int):String
	{
		var hex:String;
		
		if (listTiles.get(x + ":" + y) == null)
		{
			var data:ImageData = mapPick.getImageData(x, y, 1, 1);
			var color:Uint8ClampedArray = data.data;
			var red:Int = color[0];
			var green:Int = color[1];
			var blue:Int = color[2];
			
			hex = StringTools.hex(rgbToHex(red, green, blue), 6);
			
			listTiles.set(x + ":" + y, hex);
		}
		else
		{
			hex = listTiles.get(x + ":" + y);
		}
		
		return hex;
	}
	
	private function rgbToHex(R, G, B):Int
	{
		return (R & 0xFF) << 16 | (G & 0xFF) << 8 | (B & 0xFF);
	}
}